<template>
  <div class="login_container">
    <el-row>
      <el-col :span="11" :xs="0"></el-col>
      <el-col :span="13" :xs="24">
        <el-form class="login_from" :model="loginForm" :rules="rules" label-width="80px" label-suffix=":" ref="loginForms" status-icon>
          <h1>请登录</h1>
          <h2>欢迎来到vue3</h2>
          <el-form-item label="用户名" class="item_label" prop="userName">
            <el-input placeholder="请输入用户名" :prefix-icon="User" v-model="loginForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" :prefix-icon="Lock" placeholder="请输入密码" v-model="loginForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="login_btn" size="default" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/userStore'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElNotification, type FormInstance, type FormRules } from 'element-plus'
import { getHour } from '@/utils/time'
import type { loginForm } from '@/api/user/type'
//收集账号与密码数据
let loginForm = reactive<loginForm>({ userName: 'system', password: '111111.' })

//表单校验
//prop和v-model的值必须一致
//trigger: blur 当选择器的输入框失去焦点时触发
//trigger: focus 当选择器的输入框获得焦点时触发
//trigger: change 仅当 modelValue 改变时，当输入框失去焦点或用户按Enter时触发
//trigger: input 在 Input 值改变时触发
//trigger: clear 在点击由 clearable 属性生成的清空按钮时触发
//required代表该字段必须校验
//min：文本长度至少
//max：文本长度至多
let rules = reactive<FormRules<loginForm>>({
  userName: [
    {
      validator: userNameRule,
      trigger: 'change',
    },
  ],
  password: [
    {
      validator: passwordRule,
      trigger: 'change',
    },
  ],
})
function userNameRule(rule: any, value: any, callback: any) {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (!value) {
    callback(new Error('账号不能为空'))
  }
  if (!/^[\u4e00-\u9fa5A-Za-z0-9]{3,10}$/.test(value)) {
    callback(new Error('账号必须为汉字、字母、数字拼写，长度3-10位之间'))
  }
  callback()
}
function passwordRule(rule: any, value: any, callback: any) {
  if (!value) {
    callback(new Error('密码不能为空'))
  }
  if (!/^(?=.*[#@.]).*$/.test(value)) {
    callback(new Error('至少包含一个字符:.@#'))
  }
  if (!/^[A-Za-z0-9#@.]{6,10}$/.test(value)) {
    callback(new Error('必须为字符、字母、数字拼写，长度为6-10位之间'))
  }
  callback()
}

//调用登录接口
const loginForms = ref<FormInstance | undefined>()
const userStore = useUserStore()
const $router = useRouter()
const $route = useRoute()
async function login() {
  //校验不通过，不调用登录
  if (!loginForms.value) return
  // 异步使用await的方式等待校验完成
  const valid = await new Promise<boolean>((resolve) => {
    loginForms.value!.validate((valid) => {
      resolve(valid)
    })
  })
  // 校验不通过，直接返回
  if (!valid) return

  //发送登录请求
  //请求成功-》首页展示
  //请求失败-》提示错误
  try {
    await userStore.userLogin(loginForm)
    //登录时判断是否是从退出登录过来的，如果是，query参数中会带有redirect属性
    let redirect: any = $route.query.redirect
    $router.push(redirect || '/home')
    ElNotification({
      title: 'HI,' + getHour(),
      message: '登陆成功',
      type: 'success',
    })
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
}

.login_from {
  position: relative;
  top: 20vh;
  left: 10vh;
  width: 80%;
  padding: 30px;
  background: url('@/assets/images/login_form.png') no-repeat;
  background-size: cover;

  :deep(.el-form-item__label) {
    font-size: 18px;
    color: white;
  }

  h1 {
    font-size: 40px;
    color: white;
  }

  h2 {
    margin: 20px 0;
    font-size: 25px;
    color: white;
  }

  .login_btn {
    width: 50%;
    margin: 0 auto;
  }
}
</style>
